<?php

class Api_Model_UserMapper {
	protected $_db_table;

	public function __construct() {
		$this->_db_table = new Api_Model_DbTable_User();
	}

	public function getUserById($user_id) {
		$result = $this->_db_table->find($user_id);

		if(count($result) == 0) {
			throw new Exception(json_encode(array('meta' => 'Not found')),404);
		}

		$row = $result->current();
		$user = $row->toArray();

		$this->db_photo = new Api_Model_DbTable_Photo();
		$s_photo = $this->db_photo->select()->from('photos', array('*'))->where('user_id = ?', $user_id);
		$re_photo = $this->db_photo->fetchAll($s_photo);
		$count_photo = count($re_photo);

		$this->db_friend = new Api_Model_DbTable_Friend();
		$s_fr = $this->db_friend->select()->from('friends', array('*'))->where('user_id = ?', $user_id)
		->where('status = ?', 'friend');
		$re_fr = $this->db_friend->fetchAll($s_fr);
		$count_fr = count($re_fr);

		$json = array('user' => $user,
                        'count' => array('photo_count' => $count_photo,
                                                 'friend_count' => $count_fr));

		return $json;
	}

	public function getOtherUserById($user_id, $other_user_id) {
		$select = $this->_db_table->select()->from('users', array('*'))->where('user_id = ?', $other_user_id);
		$result = $this->_db_table->fetchAll($select);
		$row = $result->current();
		if(count($result) == 0) {
			throw new Exception(json_encode(array('meta' => 'Not found')),404);
		}

		$this->db_friend = new Api_Model_DbTable_Friend();

		$se_friend_a = $this->db_friend->select()->from('friends', array('*'))
		->where('user_id = ?', $user_id)->where('friend_id = ?', $other_user_id);
		$re_friend_a = $this->db_friend->fetchAll($se_friend_a);

		$se_friend_b = $this->db_friend->select()->from('friends', array('*'))
		->where('user_id = ?', $other_user_id)->where('friend_id = ?', $user_id);
		$re_friend_b = $this->db_friend->fetchAll($se_friend_b);


		$this->db_photo = new Api_Model_DbTable_Photo();
		$s_photo = $this->db_photo->select()->from('photos', array('*'))->where('user_id = ?', $other_user_id);
		$re_photo = $this->db_photo->fetchAll($s_photo);
		$count_photo = count($re_photo);

		$s_fr = $this->db_friend->select()->from('friends', array('*'))->where('user_id = ?', $other_user_id)
		->where('status = ?', 'friend');
		$re_fr = $this->db_friend->fetchAll($s_fr);
		$count_fr = count($re_fr);

		if(count($re_friend_a) == 0 && count($re_friend_b) == 0) {
			$json = array('user' => $row->toArray(),
                            'count' => array('photo_count' => $count_photo,
                                                 'friend_count' => $count_fr),
                            'relation' => 0);
		} elseif(count($re_friend_a) != 0 && count($re_friend_b) == 0){
			$json = array('user' => $row->toArray(),
                            'count' => array('photo_count' => $count_photo,
                                                 'friend_count' => $count_fr),
                            'relation' => 2);
		} elseif(count($re_friend_a) == 0 && count($re_friend_b) != 0){
			$json = array('user' => $row->toArray(),
                            'count' => array('photo_count' => $count_photo,
                                                 'friend_count' => $count_fr),
                            'relation' => 3);
		} elseif(count($re_friend_a) != 0 && count($re_friend_b) != 0){
			$json = array('user' => $row->toArray(),
                            'count' => array('photo_count' => $count_photo,
                                                 'friend_count' => $count_fr),
                            'relation' => 1);
		}
		return $json;
	}

	public function createUser($user){

		$db_table = new Api_Model_DbTable_User();

		$select = $this->_db_table->select()->from('users', array('user_id'))->where('username = ?', $user['username']);

		$result = $this->_db_table->fetchAll($select);

		if(count($result) == 0 && $user['password'] != "") {
			//conflict email
			$select_email = $this->_db_table->select()->from('users', array('user_id'))->where('email = ?', $user['email']);

			$result_email = $this->_db_table->fetchAll($select_email);

			if(count($result_email) == 0) {

				date_default_timezone_set('Asia/Ho_Chi_Minh');
				$currentDateTime = date('Y-m-d H-i-s');
				$currentDate = date('Y-m-d');
				$currentTime = date('H-i-s');
				//xử lý avatar
				$structure = APPLICATION_PATH."/../public/images/".$user['username']."/".$currentDate."/";
				//                var_dump($structure);
				$avatar_base64 = base64_decode($user['profile_picture']);
				$avatar_img = imagecreatefromstring($avatar_base64);
				if (!mkdir($structure, 0777, true)){
					mkdir($structure, 0777, true);
				}

				if ($avatar_img != FALSE){
					imagejpeg($avatar_img, $structure.$currentTime.'.jpg');
					$user['profile_picture'] = 'images/'.$user['username'].'/'.$currentDate.'/'.$currentTime.'.jpg';
				}

				$affectedRow = $db_table->insert($user);

				if ($affectedRow){

					$select = $this->_db_table->select()->from('users', array('*'))->where('username = ?', $user['username']);
					$result_id = $this->_db_table->fetchAll($select);
					$row = $result_id->current();

					//                date_default_timezone_set('Asia/Ho_Chi_Minh');
					//                $currentDateTime = date('Y-m-d H-i-s');
					$this->_db_table->update(array('created_time' => $currentDateTime),
					array('user_id = ?' => $row->user_id));
					$this->_db_table->update(array('last_login' => $currentDateTime),
					array('user_id = ?' => $row->user_id));

					$token = array(
                        'user' => array('user_id' => $row->user_id,
                            'username' => $row->username,
                            'fullname' => $row->fullname,
                            'profile_picture' => $row->profile_picture),
                        'access_token' => md5(md5($row->username).md5($row->password))
					);

					return $token;
				} else {
					throw new Exception('Internal Server Error' ,500);
				}
			} elseif (count($result_email) != 0){
				throw new Exception(json_encode(array('meta' => 'Not Acceptable')),406);
			}

		} elseif (count($result) != 0){
			throw new Exception(json_encode(array('meta' => 'Conflict')),409);
		} else {
			throw new Exception(json_encode(array('meta' => 'OK')),200);
		}

	}

	public function getCheckInLocation($user_id) {
		$this->db_photo = new Api_Model_DbTable_Photo();
		$s_lo = $this->db_photo->select()->from('photos', array('*'))
		->where('user_id = ?', $user_id)
		->where('location_id IS NOT NULL');
		$re_lo = $this->db_photo->fetchAll($s_lo);
		if(count($re_lo) == 0) {
			throw new Exception(json_encode(array('meta' => 'Not found')),404);
		} else {
			foreach ($re_lo as $row) {
				// $row should be a Zend_Db_Table_Row object
				// cast to array
				$this->db_location = new Api_Model_DbTable_Location();
				$select = $this->db_location->select()->from('locations', array('*'))
				->where('location_id = ?', $row->location_id);
				$result = $this->db_location->fetchAll($select);
				$rl = $result->current();

				$this->db_city = new Api_Model_DbTable_City();
				$s_city = $this->db_city->select()->from('cities', array('*'))->where('city_id = ?', $rl->city_id);
				$re_city = $this->db_city->fetchAll($s_city);
				$row_city = $re_city->current();

				$location = array('location_id' => $rl->location_id,
                                  'name' => $rl->name,
                                  'description' => $rl->description,
                                  'latitude' => $rl->latitude,
                                  'longitude' => $rl->longitude,
                    "city" => array('city_id' => $row_city->city_id, 'name' => $row_city->name));

				$json[] = array('location' => $location);

			}

			return $json;
		}
	}

	public function updateUser($user, $user_id){

		$select = $this->_db_table->select()->from('users', array('*'))->where('user_id = ?', $user_id);
		$result_id = $this->_db_table->fetchAll($select);
		$row = $result_id->current();
		$username = $row->username;
		$select_email = $this->_db_table->select()->from('users', array('user_id'))->where('email = ?', $user['email'])
		->where('user_id != ?', $user_id);
		$result_email = $this->_db_table->fetchAll($select_email);

		if(count($result_email) == 0) {
			if($user['profile_picture'] != ""){

				$mask = APPLICATION_PATH."/../public/".$row->profile_picture;
				array_map( "unlink", glob($mask));

				date_default_timezone_set('Asia/Ho_Chi_Minh');
				$currentDateTime = date('Y-m-d H-i-s');
				$currentDate = date('Y-m-d');
				$currentTime = date('H-i-s');
				//xử lý avatar
				$structure = APPLICATION_PATH."/../public/images/".$username."/".$currentDate."/";
				//            var_dump($structure);
				$avatar_base64 = base64_decode($user['profile_picture']);
				$avatar_img = imagecreatefromstring($avatar_base64);
				if (!mkdir($structure, 0777, true)){
					mkdir($structure, 0777, true);
				}

				if ($avatar_img != FALSE){
					imagejpeg($avatar_img, $structure.$currentTime.'.jpg');
					$user['profile_picture'] = 'images/'.$username.'/'.$currentDate.'/'.$currentTime.'.jpg';
				}
			}
			$where = array('user_id = "'.$user_id.'"');
			$this->_db_table->update(array('profile_picture' => $user['profile_picture']), $where);
			$this->_db_table->update(array('email' => $user['email']), $where);
			$this->_db_table->update(array('fullname' => $user['fullname']), $where);
			$this->_db_table->update(array('address' => $user['address']), $where);
			$this->_db_table->update(array('sex' => $user['sex']), $where);
			$this->_db_table->update(array('phone' => $user['phone']), $where);
			$this->_db_table->update(array('dob' => $user['dob']), $where);

			$s = $this->_db_table->select()->from('users', array('*'))->where('user_id = ?', $user_id);
			$re= $this->_db_table->fetchAll($s);
			$ro = $re->current();

			$return = array(
                'profile_picture' => $ro->profile_picture,
                'fullname' => $ro->fullname
			);

			return $return;

		} else{
			throw new Exception(json_encode(array('meta' => 'Conflict')),409);
		}

	}

	public function loginUser($user){

		if($user['username'] != "" && $user['password'] != ""){
			$db=Zend_Registry::get('DB');
			$authAdapter=new Zend_Auth_Adapter_DbTable($db);
			$authAdapter->setTableName('users')
			->setIdentityColumn('username')
			->setCredentialColumn('password');
			$authAdapter->setIdentity($user['username'])
			->setCredential($user['password']);
			$auth= Zend_Auth::getInstance();

			$result=$auth->authenticate($authAdapter);

			 
			if ($result->isValid()) {
				$select = $this->_db_table->select()->from('users', array('*'))->where('username = ?', $user['username']);
				$result_id = $this->_db_table->fetchAll($select);
				$row = $result_id->current();

				date_default_timezone_set('Asia/Ho_Chi_Minh');
				$currentDateTime = date('Y-m-d H-i-s');
				$this->_db_table->update(array('last_login' => $currentDateTime),
				array('user_id = ?' => $row->user_id));

				$token = array(
                        'user' => array('user_id' => $row->user_id,
                            'username' => $row->username,
                            'fullname' => $row->fullname,
                            'profile_picture' => $row->profile_picture),
                        'access_token' => md5(md5($row->username).md5($row->password))
				);
				return $token;
			}else{
				throw new Exception(json_encode(array('meta' => 'Not found')),404);
			}
		}else{
			throw new Exception(json_encode(array('meta' => 'Bad request')),400);
		}
	}

	public function checkLogin($token){

		$select = $this->_db_table->select()->from('users', array('*'))->where('md5(CONCAT(md5(username),md5(password))) = ?', $token);
		$result = $this->_db_table->fetchAll($select);

		if (count($result) != 0){
			return 'TRUE';
		} else {
			return 'FALSE';
		}
	}

	public function changepassUser($old_password, $new_password, $user_id){
		$select1 = $this->_db_table->select()->from('users', array('*'))->where('password = ?', $old_password);

		$result1 = $this->_db_table->fetchAll($select1);

		if(count($result1) == 0){
			throw new Exception(json_encode(array('meta' => 'Not Acceptable')),406);
		}else{
			$where = array('user_id = "'.$user_id.'"');
			$result = $this->_db_table->update(array('password' => $new_password), $where);

			$select = $this->_db_table->select()->from('users', array('*'))->where('user_id = ?', $user_id);
			$result_id = $this->_db_table->fetchAll($select);
			$row = $result_id->current();

			if($result){
				date_default_timezone_set('Asia/Ho_Chi_Minh');
				$currentDateTime = date('Y-m-d H-i-s');
				$this->_db_table->update(array('updated_time' => $currentDateTime),
				array('user_id = ?' => $user_id));

				$token = array(
                    'user_id' => $user_id,
                    'access_token' => md5(md5($row->username).md5($row->password))
				);
				return $token;
			} else {
				throw new Exception('Internal Server Error' ,500);
			}
		}



	}

	public function updateavatarUser($picture_base64, $user_id){
		$select = $this->_db_table->select()->from('users', array('*'))->where('user_id = ?', $user_id);
		$result_id = $this->_db_table->fetchAll($select);
		$row = $result_id->current();
		$username = $row->username;


		$mask = APPLICATION_PATH."/../public/".$row->profile_picture;
		array_map("unlink", glob($mask));

		date_default_timezone_set('Asia/Ho_Chi_Minh');
		$currentDateTime = date('Y-m-d H-i-s');
		$currentDate = date('Y-m-d');
		$currentTime = date('H-i-s');
		//xử lý avatar
		if ($picture_base64['profile_picture'] != ""){
			$structure = APPLICATION_PATH."/../public/images/".$username."/".$currentDate."/";
			//            var_dump($structure);
			$avatar_base64 = base64_decode($picture_base64['profile_picture']);
			$avatar_img = imagecreatefromstring($avatar_base64);
			if (!mkdir($structure, 0777, true)){
				mkdir($structure, 0777, true);
			}

			if ($avatar_img != FALSE){
				imagejpeg($avatar_img, $structure.$currentTime.'.jpg');
				$picture = 'images/'.$username.'/'.$currentDate.'/'.$currentTime.'.jpg';
			}
			$profile_picture = array('profile_picture' => $picture);
			$where = array('user_id = ?' => $user_id);
			$this->_db_table->update($profile_picture, $where);
			$this->_db_table->update(array('updated_time' => $currentDateTime), array('user_id = ?' => $user_id));

			return $profile_picture;
		} else{
			$profile_picture = array('profile_picture' => "");
			$where = array('user_id = ?' => $user_id);
			$this->_db_table->update($profile_picture, $where);
			$this->_db_table->update(array('updated_time' => $currentDateTime), array('user_id = ?' => $user_id));

			return $profile_picture;
		}
	}

	public function updateCoverUser($picture_base64, $user_id){
		$select = $this->_db_table->select()->from('users', array('*'))->where('user_id = ?', $user_id);
		$result_id = $this->_db_table->fetchAll($select);
		$row = $result_id->current();
		$username = $row->username;


		$mask = APPLICATION_PATH."/../public/".$row->cover_picture;
		array_map("unlink", glob($mask));

		date_default_timezone_set('Asia/Ho_Chi_Minh');
		$currentDateTime = date('Y-m-d H-i-s');
		$currentDate = date('Y-m-d');
		$currentTime = date('H-i-s');
		//xử lý avatar
		if ($picture_base64['cover_picture'] != ""){
			$structure = APPLICATION_PATH."/../public/images/".$username."/".$currentDate."/";
			//            var_dump($structure);
			$avatar_base64 = base64_decode($picture_base64['cover_picture']);
			$avatar_img = imagecreatefromstring($avatar_base64);
			if (!mkdir($structure, 0777, true)){
				mkdir($structure, 0777, true);
			}

			if ($avatar_img != FALSE){
				imagejpeg($avatar_img, $structure.$currentTime.'.jpg');
				$picture = 'images/'.$username.'/'.$currentDate.'/'.$currentTime.'.jpg';
			}
			$cover_picture = array('cover_picture' => $picture);
			$where = array('user_id = ?' => $user_id);
			$this->_db_table->update($cover_picture, $where);
			$this->_db_table->update(array('updated_time' => $currentDateTime), array('user_id = ?' => $user_id));

			return $cover_picture;
		} else{
			$cover_picture = array('cover_picture' => "");
			$where = array('user_id = ?' => $user_id);
			$this->_db_table->update($cover_picture, $where);
			$this->_db_table->update(array('updated_time' => $currentDateTime), array('user_id = ?' => $user_id));

			return $cover_picture;
		}
	}


	public function mail($email){
		//$select = 'SELECT * FROM users WHERE md5(CONCAT(md5(username),md5(password))) = "'.$token.'';
		$select = $this->_db_table->select()->from('users', array('*'))->where('email = ?', $email);
		$result = $this->_db_table->fetchAll($select);

		if (count($result) != 0){
			$micro = (int)(microtime(true)*1000);
			$password = array('password' => md5($micro));
			$where = array('email = ?' => $email);
			$this->_db_table->update($password, $where);
			return $micro;
		} else {
			throw new Exception(json_encode(array('meta' => 'Not found')),404);
		}
	}

	public function searchUser($user_id, $username) {
		$select = $this->_db_table->select()->from('users', '*')
		->where('username LIKE ?', '%'.$username.'%');
		$result = $this->_db_table->fetchAll($select);

		if(count($result) == 0) {
			throw new Exception(json_encode(array('meta' => 'Not found')),404);
		} else {
			foreach ($result as $row) {
				// $row should be a Zend_Db_Table_Row object
				// cast to array
				$rowArray = $row->toArray();
				$se_friend_a = $this->db_friend->select()->from('friends', array('*'))
				->where('user_id = ?', $user_id)->where('friend_id = ?', $rowArray['user_id']);
				$re_friend_a = $this->db_friend->fetchAll($se_friend_a);

				$se_friend_b = $this->db_friend->select()->from('friends', array('*'))
				->where('user_id = ?', $rowArray['user_id'])->where('friend_id = ?', $user_id);
				$re_friend_b = $this->db_friend->fetchAll($se_friend_b);

				if(count($re_friend_a) == 0 && count($re_friend_b) == 0) {
					$user= array('user_id' => $rowArray['user_id'],
                                'username' => $rowArray['username'],
                                'fullname' => $rowArray['fullname'],
                                'profile_picture' => $rowArray['profile_picture'],
                                    'relation' => 0);
				} elseif(count($re_friend_a) != 0 && count($re_friend_b) == 0){
					$user= array('user_id' => $rowArray['user_id'],
                                'username' => $rowArray['username'],
                                'fullname' => $rowArray['fullname'],
                                'profile_picture' => $rowArray['profile_picture'],
                                    'relation' => 2);
				} elseif(count($re_friend_a) == 0 && count($re_friend_b) != 0){
					$user= array('user_id' => $rowArray['user_id'],
                                'username' => $rowArray['username'],
                                'fullname' => $rowArray['fullname'],
                                'profile_picture' => $rowArray['profile_picture'],
                                    'relation' => 3);
				} elseif(count($re_friend_a) != 0 && count($re_friend_b) != 0){
					$user= array('user_id' => $rowArray['user_id'],
                                'username' => $rowArray['username'],
                                'fullname' => $rowArray['fullname'],
                                'profile_picture' => $rowArray['profile_picture'],
                                    'relation' => 1);
				}

				$json[] = array('user' => $user);

			}
			return $json;
		}
	}
}
